
package com.scalar.chiptrack.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.util.HashMap;

import org.apache.commons.dbcp.BasicDataSource;

import com.scalar.ScalarException;
import com.scalar.chiptrack.commons.Constants;

/**
 *
 * @author Balaram Putta
 * @version
 */
public final class DataSource
{
    private static HashMap<String, BasicDataSource> sDataSourceMap = new HashMap<String, BasicDataSource>();


    public static Connection getConnection() throws ScalarException, SQLException
    {
        return getConnection( Constants.DATASOURCE_TYPE_LOCAL );
    }


    public static Connection getConnection( int datasourceType ) throws ScalarException, SQLException
    {
        BasicDataSource basicDataSource = ( BasicDataSource ) sDataSourceMap.get( datasourceType+"" );

        if( basicDataSource == null )
        {
            basicDataSource = createDataSource( datasourceType );
            sDataSourceMap.put( datasourceType+"", basicDataSource );
        }

        if( datasourceType == Constants.DATASOURCE_TYPE_GREAT_PLAINS && basicDataSource.getConnection().isClosed() )
        {
        	sDataSourceMap.remove( datasourceType+"" );
        	basicDataSource = createDataSource( datasourceType );
        	sDataSourceMap.put( datasourceType+"", basicDataSource );
        }
        return basicDataSource.getConnection();
    }


    /**
     * Creates datasource based on the datasource type
     *
     * @return Either LocalDatabaseSource or GraatPlainsDataSource
     * @throws ScalarException
     */
    private static BasicDataSource createDataSource( int datasourceType ) throws ScalarException {

        DataSourceConfig config = new DataSourceConfig( datasourceType );

        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUrl (config.getUrl());
        dataSource.setDriverClassName (config.getDriverClass());
        dataSource.setUsername (config.getUserName());
        dataSource.setPassword (config.getPassword());
        dataSource.setMaxActive (config.getMaxConn());
        dataSource.setDefaultAutoCommit (config.getAutoCommit());

        System.out.println ("\nDataSource URL... " + config.getUrl() + "\n");

        return dataSource;
    }


    // test
    public static void main(String[] args) {

        final String SELECT_USERS = "Select * from User_Table";
        
        Connection conn = null;
        Statement stmt = null;
        ResultSet rset = null;

        try {

            System.out.println("Creating connection.");
            conn = DataSource.getConnection();

            System.out.println("Creating statement.");
            stmt = conn.createStatement();

            System.out.println("Executing statement.");
            rset = stmt.executeQuery(SELECT_USERS);

            System.out.println("Results:");

            int numcols = rset.getMetaData().getColumnCount();
            while(rset.next()) {
                for(int i=1;i<=numcols;i++) {
                    System.out.print("\t" + rset.getString(i));
                }
                System.out.println("");
            }
        }
       	catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            try { rset.close(); } catch(Exception e) { }
            try { stmt.close(); } catch(Exception e) { }
            try { conn.close(); } catch(Exception e) { }
        }
    }
}